package com.weetop.akly.activity;

import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.weetop.akly.R;
import com.weetop.akly.activity.communicationIndex.IndexFragment;
import com.weetop.akly.activity.meessage.MsgMainFragment;
import com.weetop.akly.activity.mine.MineFragment;
import com.weetop.akly.activity.work.WorkFragment;
import com.weetop.akly.base.BaseActivity;
import com.weetop.akly.base.mvp.BaseModel;
import com.weetop.akly.bean.AccountInfoBean;
import com.weetop.akly.bean.PostMessage;
import com.weetop.akly.bean.RongImUserInfoBean;
import com.weetop.akly.bean.TabEntity;
import com.weetop.akly.presenter.AccountInfoPresent;
import com.weetop.akly.utils.Tablayout.CommonTabLayout;
import com.weetop.akly.utils.Tablayout.listener.CustomTabEntity;
import com.weetop.akly.utils.Tablayout.listener.OnTabSelectListener;
import com.weetop.akly.view.AccountView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

public class MainActivity extends BaseActivity<AccountInfoPresent> implements AccountView {

    @BindView(R.id.tl_main1)
    CommonTabLayout tlMain1;

    private Fragment[] fragments;
    private MsgMainFragment messageFragment;
    private WorkFragment workFragment;
    private IndexFragment indexFragment;
    private MineFragment mineFragment;
    private ArrayList<CustomTabEntity> mTabEntities1 = new ArrayList<>();


    @Override
    protected AccountInfoPresent createPresenter() {
        return new AccountInfoPresent(this, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //沉浸式状态栏
        QMUIStatusBarHelper.translucent(this);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
        initFragment();
        switchfragment(messageFragment);
        //获取个人信息资料
        mPresenter.getAccountInfo();
        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {

            /**
             * 获取设置用户信息. 通过返回的 userId 来封装生产用户信息.
             * @param userId 用户 ID
             */
            @Override
            public UserInfo getUserInfo(String userId) {
                mPresenter.getRongIMUserInfo(userId);
                return null;
            }

        }, true);
        Log.e(TAG, "onCreate: " + AppUtils.getAppSignatureSHA1());
    }

    @Override
    public void getAccountInfoSuccess(BaseModel<AccountInfoBean> o) {
        //保存个人信息
        myApplication.setAccountInfoBean(o.getData());
    }

    @Override
    public void getRongIMUserInfoSuccess(BaseModel<RongImUserInfoBean> o, String userId) {
        RongImUserInfoBean data = o.getData();
        UserInfo userInfo = new UserInfo(userId, data.getName(), Uri.parse(data.getPhoto()));
        RongIM.getInstance().refreshUserInfoCache(userInfo);
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(PostMessage event) {
        if (event.getKey().equals("tocart")) {
            Log.e(TAG, "receiveEvent: ");
//            switchfragment(cartFragment);
            tlMain1.setCurrentTab(3);
        }
    }

    /**
     * 初始化 fragment  数据
     */
    private void initFragment() {
        messageFragment = new MsgMainFragment();
        workFragment = new WorkFragment();
        indexFragment = new IndexFragment();
        mineFragment = new MineFragment();
        fragments = new Fragment[]{messageFragment, workFragment, indexFragment, mineFragment};

        mTabEntities1.add(new TabEntity("消息", R.mipmap.msg_selected, R.mipmap.msg_unselect));
        mTabEntities1.add(new TabEntity("工作", R.mipmap.work_selected, R.mipmap.work_unselect));
        mTabEntities1.add(new TabEntity("通讯录", R.mipmap.index_selected, R.mipmap.index_unselect));
        mTabEntities1.add(new TabEntity("我的", R.mipmap.mine_selected, R.mipmap.mine_unselected));
        tlMain1.setTabData(mTabEntities1);
        //底部导航切换
        tlMain1.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                switchfragment(fragments[position]);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
    }

    /**
     * 选择fragment
     *
     * @param fragment
     */
    private void switchfragment(Fragment fragment) {
        // 设置一个默认值
        if (fragment == null) {
            fragment = messageFragment;
        }
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        for (Fragment fragment1 : fragments) {
            if (fragment1 != fragment) {
                if (fragment1 != null && !fragment1.isHidden() && fragment1.isAdded()) {
                    ft.hide(fragment1);
                }
            }
        }

        if (fragment.isAdded() && fragment.isHidden()) {
            ft.show(fragment);
        } else {
            if (!fragment.isAdded()) {
                ft.add(R.id.frame_blank, fragment);
            }
        }
        ft.commitAllowingStateLoss();
    }

    /**
     * 双击退出程序
     */
    private long mExitTime;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void showError(String msg) {
        ToastUtils.showShort(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RongIM.getInstance().disconnect();
    }
}
